package com.yiren.manager.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.yiren.core.security.DESUtils;

public class CookieUtil {

	/**
	 * Cookie
	 * @return
	 */
	public static <T> void setJsonCookie(String key, T value) {
		String json = JSON.toJSONString(value);
		json = DESUtils.encode("YIREN", json);
		Cookie cookie = new Cookie(key, json);
		cookie.setPath("/");
		cookie.setMaxAge(60 * 60 * 24 * 365);

		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();
		response.addCookie(cookie);
	}

	/**
	 * Cookie
	 * @return
	 */
	public static <T> T getJsonCookie(String key, Class<T> cls) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();

		Cookie[] cookies = request.getCookies();
		if (cookies == null)
			return null;

		for (Cookie cookie : cookies) {
			if (key.equals(cookie.getName())) {
				String json = cookie.getValue();
				json = DESUtils.decode("yiren", json);
				T value = JSON.parseObject(json, cls);
				return value;
			}
		}
		return null;
	}

	/**
	 * Cookie
	 * 
	 * @return
	 */
	public static void setCookie(String name, Object value) {
		Cookie cookie = new Cookie(name, value.toString());
		cookie.setMaxAge(60 * 60 * 24 * 365);
		cookie.setPath("/");
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();
		response.addCookie(cookie);
	}

	/**
	 * Cookie取得
	 * 
	 * @return
	 */
	public static String getCookie(String key) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();

		Cookie[] cookies = request.getCookies();
		if (cookies == null)
			return null;

		for (Cookie cookie : cookies) {
			if (key.equals(cookie.getName())) {
				String value = cookie.getValue();
				return value;
			}
		}
		return null;
	}
}
